package com.xzcs.service.weixin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.weixin.WxAutoRespMapper;
import com.xzcs.mapper.weixin.WxResponseMapper;
import com.xzcs.service.BaseService;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.web.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class WxAutoRespService extends BaseService {

	@Autowired
	private WxAutoRespMapper autoRespMapper;
	@Autowired
	public WxResponseMapper wxResponseMapper;

	public PageInfo<Map<String, Object>> findAutoMsgs(HttpServletRequest request){
		String pageNum = RequestUtils.getValue(request, "page");//页数
		String pageSize = RequestUtils.getValue(request, "rows");//每页条数
		pageNum = pageNum.equals("") ? "1" : pageNum;
		pageSize = pageSize.equals("") ? getDefaultPageSize() : pageSize;
		Map<String, Object> params = RequestUtils.getRequestMap(request);
		PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
		List<Map<String, Object>> list = autoRespMapper.findAutoMsgs(params);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		return page;
	}

	public Map<String, Object> findAutoMsg(HttpServletRequest request){
		String id = RequestUtils.getValue(request, "id");
		return autoRespMapper.findAutoMsg(id);
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveAutoMsg(HttpServletRequest request){
		Map<String, Object> user = this.getUser(request);
		String method = RequestUtils.getValue(request, "method");
		Map<String, Object> params = RequestUtils.getRequestMap(request);
		params.put("userId", StringUtils.get(user, "user_id"));

		if (method.equals("create")) {
			params.put("id", StringUtils.getUUID());
			autoRespMapper.insertAutoMsg(params);
		} else if (method.equals("edit")){
			autoRespMapper.updateAutoMsg(params);
		}
	}

	public void deleteAutoMsg(HttpServletRequest request){
		String id = RequestUtils.getValue(request, "id");
		autoRespMapper.deleteAutoMsg(id);
	}

	public List<Map<String, Object>> findExpandList(HttpServletRequest request){
		String accountId = RequestUtils.getValue(request, "accountId");
		List<Map<String, Object>> list = wxResponseMapper.findExpands(accountId);
		return list;
	}
}
